package com.es.easystoragesimulatedata.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.es.easystoragesimulatedata.model.StationInfo;
import com.es.easystoragesimulatedata.model.StationStatus;
import com.es.easystoragesimulatedata.service.StationInfoService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电站信息管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/station-info")
@Tag(name = "电站信息管理", description = "电站基本信息管理相关接口")
@CrossOrigin(origins = "*", allowCredentials = "false", maxAge = 3600)
@RequiredArgsConstructor
public class StationInfoController {
    
    private final StationInfoService stationInfoService;
    
    /**
     * 获取所有电站信息
     */
    @GetMapping("/list")
    @Operation(
        summary = "获取所有电站信息", 
        description = "获取系统中所有电站的完整信息，包含电站ID、名称、类型、容量、状态等"
    )
    @ApiOperationSupport(order = 1)
    public ResponseEntity<Map<String, Object>> getAllStationInfo() {
        log.info("获取所有电站信息请求");
        
        try {
            List<StationInfo> stations = stationInfoService.getAllStationInfo();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取电站信息成功");
            response.put("data", stations);
            response.put("total", stations.size());
            
            log.info("成功获取电站信息，共{}个电站", stations.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取电站信息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站信息失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 分页获取电站信息
     */
    @GetMapping("/page")
    @Operation(
        summary = "分页获取电站信息", 
        description = "分页获取电站信息，支持分页查询"
    )
    @ApiOperationSupport(order = 2)
    public ResponseEntity<Map<String, Object>> getStationInfoPage(
            @Parameter(description = "当前页码", example = "1")
            @RequestParam(defaultValue = "1") int current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") int size) {
        
        log.info("分页获取电站信息请求 - 页码: {}, 每页大小: {}", current, size);
        
        try {
            Page<StationInfo> page = stationInfoService.getStationInfoPage(current, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取电站信息成功");
            response.put("data", page.getRecords());
            response.put("total", page.getTotal());
            response.put("current", page.getCurrent());
            response.put("size", page.getSize());
            response.put("pages", page.getPages());
            
            log.info("成功分页获取电站信息 - 当前页: {}, 总页数: {}, 总记录数: {}", 
                    page.getCurrent(), page.getPages(), page.getTotal());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("分页获取电站信息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站信息失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据电站ID获取电站信息
     */
    @GetMapping("/{stationId}")
    @Operation(
        summary = "根据电站ID获取电站信息", 
        description = "根据电站ID获取指定电站的详细信息"
    )
    @ApiOperationSupport(order = 3)
    public ResponseEntity<Map<String, Object>> getStationInfoById(
            @Parameter(description = "电站ID", required = true, example = "ST001")
            @PathVariable String stationId) {
        
        log.info("根据电站ID获取电站信息请求 - 电站ID: {}", stationId);
        
        try {
            StationInfo station = stationInfoService.getStationInfoByStationId(stationId);
            
            Map<String, Object> response = new HashMap<>();
            if (station != null) {
                response.put("success", true);
                response.put("message", "获取电站信息成功");
                response.put("data", station);
                log.info("成功获取电站信息 - 电站ID: {}, 电站名称: {}", stationId, station.getStationName());
            } else {
                response.put("success", false);
                response.put("message", "未找到指定的电站信息，电站ID: " + stationId);
                response.put("data", null);
                log.warn("未找到指定的电站信息 - 电站ID: {}", stationId);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据电站ID获取电站信息失败 - 电站ID: {}, 错误信息: {}", stationId, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站信息失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据状态获取电站信息
     */
    @GetMapping("/by-status")
    @Operation(
        summary = "根据状态获取电站信息", 
        description = "根据电站状态筛选电站信息，支持的状态：已商运、已并网、建设中"
    )
    @ApiOperationSupport(order = 4)
    public ResponseEntity<Map<String, Object>> getStationInfoByStatus(
            @Parameter(description = "电站状态", required = true, example = "CONSTRUCTION", schema = @Schema(allowableValues = {"CONSTRUCTION", "GRID_CONNECTED", "COMMERCIAL_OPERATION"}))
            @RequestParam StationStatus status) {
        
        log.info("根据状态获取电站信息请求 - 状态: {}", status);
        
        try {
            List<StationInfo> stations = stationInfoService.getStationInfoByStatus(status.getDescription());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取电站信息成功");
            response.put("data", stations);
            response.put("total", stations.size());
            response.put("status", status.getDescription());
            
            log.info("成功获取状态为{}的电站信息，共{}个电站", status, stations.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据状态获取电站信息失败 - 状态: {}, 错误信息: {}", status, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站信息失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据电站名称搜索
     */
    @GetMapping("/search")
    @Operation(
        summary = "根据电站名称搜索", 
        description = "根据电站名称进行模糊搜索"
    )
    @ApiOperationSupport(order = 5)
    public ResponseEntity<Map<String, Object>> searchStationInfoByName(
            @Parameter(description = "电站名称关键词", required = true, example = "储能")
            @RequestParam String stationName) {
        
        log.info("根据电站名称搜索请求 - 关键词: {}", stationName);
        
        try {
            List<StationInfo> stations = stationInfoService.getStationInfoByName(stationName);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "搜索电站信息成功");
            response.put("data", stations);
            response.put("total", stations.size());
            response.put("keyword", stationName);
            
            log.info("成功搜索电站信息 - 关键词: {}, 结果数量: {}", stationName, stations.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据电站名称搜索失败 - 关键词: {}, 错误信息: {}", stationName, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "搜索电站信息失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 创建电站信息
     */
    @PostMapping
    @Operation(
        summary = "创建电站信息", 
        description = "创建新的电站信息"
    )
    @ApiOperationSupport(order = 6)
    public ResponseEntity<Map<String, Object>> createStationInfo(@RequestBody StationInfo stationInfo) {
        log.info("创建电站信息请求 - 电站ID: {}, 电站名称: {}", 
                stationInfo.getStationId(), stationInfo.getStationName());
        
        try {
            boolean success = stationInfoService.saveStationInfo(stationInfo);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("success", true);
                response.put("message", "创建电站信息成功");
                response.put("data", stationInfo);
                log.info("成功创建电站信息 - 电站ID: {}, 电站名称: {}", 
                        stationInfo.getStationId(), stationInfo.getStationName());
            } else {
                response.put("success", false);
                response.put("message", "创建电站信息失败");
                response.put("data", null);
                log.warn("创建电站信息失败 - 电站ID: {}", stationInfo.getStationId());
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建电站信息失败 - 电站ID: {}, 错误信息: {}", 
                    stationInfo.getStationId(), e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建电站信息失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 更新电站信息
     */
    @PutMapping
    @Operation(
        summary = "更新电站信息", 
        description = "更新指定电站的信息"
    )
    @ApiOperationSupport(order = 7)
    public ResponseEntity<Map<String, Object>> updateStationInfo(@RequestBody StationInfo stationInfo) {
        log.info("更新电站信息请求 - 电站ID: {}, 电站名称: {}", 
                stationInfo.getStationId(), stationInfo.getStationName());
        
        try {
            boolean success = stationInfoService.updateStationInfo(stationInfo);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("success", true);
                response.put("message", "更新电站信息成功");
                response.put("data", stationInfo);
                log.info("成功更新电站信息 - 电站ID: {}, 电站名称: {}", 
                        stationInfo.getStationId(), stationInfo.getStationName());
            } else {
                response.put("success", false);
                response.put("message", "更新电站信息失败");
                response.put("data", null);
                log.warn("更新电站信息失败 - 电站ID: {}", stationInfo.getStationId());
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新电站信息失败 - 电站ID: {}, 错误信息: {}", 
                    stationInfo.getStationId(), e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新电站信息失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 删除电站信息
     */
    @DeleteMapping("/{id}")
    @Operation(
        summary = "删除电站信息", 
        description = "删除指定ID的电站信息（逻辑删除）"
    )
    @ApiOperationSupport(order = 8)
    public ResponseEntity<Map<String, Object>> deleteStationInfo(
            @Parameter(description = "电站信息ID", required = true, example = "1")
            @PathVariable Long id) {
        
        log.info("删除电站信息请求 - ID: {}", id);
        
        try {
            boolean success = stationInfoService.deleteStationInfo(id);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("success", true);
                response.put("message", "删除电站信息成功");
                response.put("data", null);
                log.info("成功删除电站信息 - ID: {}", id);
            } else {
                response.put("success", false);
                response.put("message", "删除电站信息失败");
                response.put("data", null);
                log.warn("删除电站信息失败 - ID: {}", id);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除电站信息失败 - ID: {}, 错误信息: {}", id, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除电站信息失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取电站状态统计
     */
    @GetMapping("/status/statistics")
    @Operation(
        summary = "获取电站状态统计", 
        description = "获取各状态电站的数量统计信息"
    )
    @ApiOperationSupport(order = 9)
    public ResponseEntity<Map<String, Object>> getStationStatusStatistics() {
        log.info("获取电站状态统计请求");
        
        try {
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("建设中", stationInfoService.getStationCountByStatus("建设中"));
            statistics.put("已并网", stationInfoService.getStationCountByStatus("已并网"));
            statistics.put("已商运", stationInfoService.getStationCountByStatus("已商运"));
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取电站状态统计成功");
            response.put("data", statistics);
            
            log.info("成功获取电站状态统计: {}", statistics);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取电站状态统计失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站状态统计失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
}
